<script setup lang="tsx">
import type { VbenFormProps } from '@vben/common-ui';

import type { VxeGridProps } from '#/adapter/vxe-table';
import type { InterviewQuestionCategory } from '#/api/interview/category/model';

// 在组件挂载时加载父级分类下拉选项
// 使用 nextTick 确保表单已经初始化完成
import { nextTick, onMounted, watch } from 'vue';

import { useAccess } from '@vben/access';
import { Page, useVbenDrawer, useVbenModal } from '@vben/common-ui';
import { $t } from '@vben/locales';
import { addFullName, getVxePopupContainer, listToTree } from '@vben/utils';

import { Modal, Popconfirm, Space } from 'ant-design-vue';

import { useVbenVxeGrid, vxeCheckboxChecked } from '#/adapter/vxe-table';
import {
  changeCategoryStatus,
  delCategory,
  getCategoryList,
  getCategoryListWithCount,
} from '#/api/interview/category';
import { TableSwitch } from '#/components/table';

import AiCategoryModal from './ai-category-modal.vue';
import CategoryDrawer from './category-drawer.vue';
import { columns, querySchema } from './data.tsx';
import SortModal from './sort-modal.vue';

// 表单配置
const formOptions: VbenFormProps = {
  commonConfig: {
    labelWidth: 80,
    componentProps: {
      allowClear: true,
    },
  },
  schema: querySchema(),
  wrapperClass: 'grid-cols-1 md:grid-cols-2 lg:grid-cols-3 xl:grid-cols-4',
};

// 表格配置
const gridOptions: VxeGridProps = {
  checkboxConfig: {
    // 高亮
    highlight: true,
    // 翻页时保留选中状态
    reserve: true,
  },
  columns,
  height: 'auto', // 固定高度防止不断变高
  keepSource: true,
  pagerConfig: {},
  proxyConfig: {
    ajax: {
      query: async ({ page }, formValues = {}) => {
        const params = {
          pageNum: page.currentPage,
          pageSize: page.pageSize,
          ...formValues,
        };
        return await getCategoryListWithCount(params);
      },
    },
  },
  rowConfig: {
    keyField: 'categoryId',
  },
  toolbarConfig: {
    search: true,
  },
  id: 'interview-category-index',
};

const [BasicTable, tableApi] = useVbenVxeGrid({
  formOptions,
  gridOptions,
});

// 设置父级分类下拉选项
async function setupParentCategorySelect() {
  try {
    // 获取所有分类列表
    const res = await getCategoryList({ status: '0', parentId: 0 });

    // 转换为树形结构
    const treeData = listToTree(res.rows, {
      id: 'categoryId',
      pid: 'parentId',
      children: 'children',
    });

    // 添加全名，显示层级关系
    addFullName(treeData, 'categoryName', ' / ');

    // 添加"无父级"选项作为根节点
    const finalTreeData = [
      {
        categoryId: 0,
        categoryName: '无父级分类',
        children: treeData,
      },
    ];

    // 更新表单中父级分类下拉框的选项
    tableApi.formApi.updateSchema([
      {
        componentProps: {
          treeData: finalTreeData,
        },
        fieldName: 'parentId',
      },
    ]);
  } catch (error) {
    console.error('获取分类列表失败:', error);
  }
}

const [CategoryDrawerComp, drawerApi] = useVbenDrawer({
  connectedComponent: CategoryDrawer,
});

// AI分类模态框
const [AiCategoryModalComp, aiCategoryModalApi] = useVbenModal({
  connectedComponent: AiCategoryModal,
});

// 排序模态框
const [SortModalComp, sortModalApi] = useVbenModal({
  connectedComponent: SortModal,
});

function handleAdd() {
  drawerApi.setData({});
  drawerApi.open();
}

// AI生成分类
function handleAiGenerate() {
  aiCategoryModalApi.open();
}

async function handleEdit(record: InterviewQuestionCategory) {
  drawerApi.setData({ id: record.categoryId });
  drawerApi.open();
}

// 处理排序
async function handleSort() {
  try {
    // 获取当前页面的所有分类数据
    const tableData = await tableApi.grid.getTableData();
    const categories = tableData.fullData;

    if (categories.length === 0) {
      Modal.warning({
        title: '提示',
        content: '当前没有可排序的分类数据',
      });
      return;
    }

    // 打开排序模态框
    sortModalApi.setData({ categories });
    sortModalApi.open();
  } catch (error) {
    console.error('获取分类数据失败:', error);
  }
}

async function handleDelete(row: InterviewQuestionCategory) {
  // 检查是否有面试题关联
  if (row.interviewCount && row.interviewCount > 0) {
    Modal.warning({
      title: '提示',
      content: `该分类下有${row.interviewCount}个面试题，无法删除`,
    });
    return;
  }
  Modal.confirm({
    title: '提示',
    content: '确认删除该分类吗？',
    onOk: async () => {
      await delCategory([row.categoryId]);
      await tableApi.query();
    },
  });
}

function handleMultiDelete() {
  const rows = tableApi.grid.getCheckboxRecords();

  // 检查是否有面试题关联
  const hasQuestions = rows.some(
    (row: InterviewQuestionCategory) =>
      row.interviewCount && row.interviewCount > 0,
  );

  if (hasQuestions) {
    Modal.warning({
      title: '提示',
      content: '选中的分类下存在面试题，无法删除',
    });
    return;
  }

  const ids = rows.map((row: InterviewQuestionCategory) => row.categoryId);
  Modal.confirm({
    title: '提示',
    okType: 'danger',
    content: `确认删除选中的${ids.length}条记录吗？`,
    onOk: async () => {
      await delCategory(ids);
      await tableApi.query();
    },
  });
}

const { hasAccessByCodes } = useAccess();

// 状态切换
async function handleChangeStatus(record: InterviewQuestionCategory) {
  const res = await changeCategoryStatus(record.categoryId, record.status);
  if (res) {
    await tableApi.query();
  }
}

// 防抖函数
let searchTimer: NodeJS.Timeout | null = null;
function debounceSearch() {
  if (searchTimer) {
    clearTimeout(searchTimer);
  }
  searchTimer = setTimeout(() => {
    tableApi.query();
  }, 500);
}
console.log('表单值变化，自动触发查询', tableApi.formApi);

// 监听表单值变化，自动触发查询
watch(
  () => tableApi.formApi,
  () => {
    console.log('表单值变化，自动触发查询', tableApi);
    debounceSearch();
  },
  { deep: true },
);

onMounted(async () => {
  await nextTick();
  setupParentCategorySelect();
});
</script>

<template>
  <Page :auto-content-height="true">
    <BasicTable table-title="分类列表">
      <template #toolbar-tools>
        <Space>
          <a-button
            :disabled="!vxeCheckboxChecked(tableApi)"
            danger
            type="primary"
            v-access:code="['interview:category:remove']"
            @click="handleMultiDelete"
          >
            {{ $t('pages.common.delete') }}
          </a-button>
          <a-button
            type="primary"
            v-access:code="['interview:category:add']"
            @click="handleAdd"
          >
            {{ $t('pages.common.add') }}
          </a-button>
          <a-button
            type="primary"
            v-access:code="['interview:category:edit']"
            @click="handleAiGenerate"
          >
            AI生成分类
          </a-button>
          <a-button
            type="primary"
            v-access:code="['interview:category:edit']"
            @click="handleSort"
          >
            排序
          </a-button>
        </Space>
      </template>
      <template #status="{ row }">
        <TableSwitch
          v-model="row.status"
          :api="() => handleChangeStatus(row)"
          :disabled="!hasAccessByCodes(['interview:category:edit'])"
          :reload="() => tableApi.query()"
        />
      </template>
      <template #action="{ row }">
        <Space>
          <ghost-button
            v-access:code="['interview:category:edit']"
            @click.stop="handleEdit(row)"
          >
            {{ $t('pages.common.edit') }}
          </ghost-button>
          <Popconfirm
            :get-popup-container="getVxePopupContainer"
            placement="left"
            title="确认删除？"
            @confirm="handleDelete(row)"
          >
            <ghost-button
              danger
              v-access:code="['interview:category:remove']"
              @click.stop=""
            >
              {{ $t('pages.common.delete') }}
            </ghost-button>
          </Popconfirm>
        </Space>
      </template>
    </BasicTable>
    <CategoryDrawerComp @reload="tableApi.query()" />
    <AiCategoryModalComp @reload="tableApi.query()" />
    <SortModalComp @reload="tableApi.query()" />
  </Page>
</template>
